﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace QL_NOI_TRU
{
    public partial class frmconnect : DevExpress.XtraEditors.XtraForm
    {
        public string Server;
        public string UserName;
        public string Password;
        public string Database;
        string line = "";
        string c = "";
        public frmconnect()
        {
            InitializeComponent();
        }

        /// <summary>
        /// ma hoa chuoi ket noi
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string StringToBase64(string src)
        {
            byte[] b = Encoding.Unicode.GetBytes(src);
            return Convert.ToBase64String(b);
        }

        /// <summary>
        /// giai ma chuoi ket noi
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string Base64ToString(string src)
        {
            byte[] b = Convert.FromBase64String(src);
            return Encoding.Unicode.GetString(b);
        }

        /// <summary>
        /// doc chuoi ket noi duoc luu trong file
        /// </summary>

        void Loadfile()
        {
            using (StreamReader sr = new StreamReader(Application.StartupPath + "\\ConnectString.con"))
            {
                while ((line = sr.ReadToEnd().Trim()) != "")
                {

                    c = line;
                }
            }
        }



        void SaveDir()
        {
            using (StreamWriter sw = new StreamWriter(Application.StartupPath + "\\ConnectString.con"))
            {
                sw.Flush();
                sw.WriteLine(a);
            }
        }


        string a = "";


        private void cmbDatabase_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            btnOK.Enabled = true;
        }

        private void btnTestconnection_Click_1(object sender, EventArgs e)
        {
            //Quyền Windows
            if (cmbAuthentication.SelectedIndex == -1)
            {
                cmbDatabase.Items.Clear();
                SqlConnection con = new SqlConnection(String.Format("Data Source={0};Initial Catalog=master;Integrated Security=True;", txtServer.Text));
                SqlCommand cmd = new SqlCommand("SP_DATABASES", con);
                //SP_DATABASES là một store procedure có sẵn của sql server để lấy ra tất cả csdl trong sql server
                SqlDataReader reader;
                try
                {
                    con.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        cmbDatabase.Items.Add(reader[0].ToString());
                    }
                    cmbDatabase.Enabled = true;
                    MessageBox.Show("Kết nối dữ liệu thành công!", "Thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception)
                {

                    MessageBox.Show("Lỗi, vui lòng thử lại!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();

                    con.Dispose();
                    cmd.Dispose();
                }
            }

            //Quyền SQL Server
            //     if (cmbAuthentication.SelectedIndex == 0)
            else
            {
                cmbDatabase.Items.Clear();
                SqlConnection con = new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3};", txtServer.Text, cmbDatabase.Text, txtUser.Text, txtPassword.Text));
                SqlCommand cmd = new SqlCommand("SP_DATABASES", con);
                SqlDataReader reader;

                try
                {
                    con.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        cmbDatabase.Items.Add(reader[0].ToString());
                    }
                    cmbDatabase.Enabled = true;
                    MessageBox.Show("Kết nối dữ liệu thành công!", "thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //      throw new NullReferenceException();
                }
                catch (Exception)
                {
                    MessageBox.Show("Lỗi dữ liệu, vui lòng thử lại!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();

                    con.Dispose();
                    cmd.Dispose();
                }
            }
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOK_Click_1(object sender, EventArgs e)
        {
            if (cmbAuthentication.SelectedIndex == 1)
            {
                a = String.Format("server={0};database={1}", txtServer.Text, cmbDatabase.Text);
                MessageBox.Show(a);
                a = StringToBase64(a);
                SaveDir();

            }
            else
            {
                a = String.Format("server={0};database={1};uid={2};password={3}", txtServer.Text, cmbDatabase.Text, txtUser.Text, txtPassword.Text);
                MessageBox.Show(a);
                a = StringToBase64(a);
                SaveDir();
            }
            frmDangnhap frmDN = new frmDangnhap { Text = "Đăng nhập" };
            this.Hide();
            frmDN.ShowDialog();
        }

        private void cmbDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbAuthentication.SelectedIndex == 1)
            {
                txtUser.Enabled = false;
                txtPassword.Enabled = false;
            }
            else
            {
                txtUser.Enabled = true;
                txtPassword.Enabled = true;
            }
        }

        private void frmconnect_Load(object sender, EventArgs e)
        {
            cmbAuthentication.SelectedIndex = 0;
            Loadfile();
            c = Base64ToString(c);
            SqlConnection conn = new SqlConnection(c);
            try
            {
                conn.Open();
                MessageBox.Show("Kết nối dữ liệu thành công!", "thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);
                frmDangnhap frmDN = new frmDangnhap();
                frmDangnhap.stringConn = c;
                frmDN.Text = "Đăng nhập";
                this.Hide();
                frmDN.ShowDialog();

            }
            catch (Exception ex)
            {
#if DEBUG
                MessageBox.Show(ex.Message);
                MessageBox.Show("Lỗi connect dữ liệu, vui lòng thử lại!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
#else 
                MessageBox.Show("lỗi kết nối dữ liệu! ");
#endif
            }
        }

    }
}